import { message } from "antd";
import axios from "axios";
import store from "store2";
const isDev = process.env.NODE_ENV === "development";
const instance = axios.create({
  baseURL: isDev ? "http://localhost:8888" : "http://localhost:8888",
});

//请求拦截器
instance.interceptors.request.use((config) => {
  const storeUsers = store.get("shopping");

  config.headers.authorization = storeUsers;

  return config;
});

//响应拦截器
instance.interceptors.response.use((response) => {
  if (response.data.code === "401") {
    message.warning("登录过期，请重新登录");
    store.remove("users");
    window.location.href = "/shopping"; //跳转到购物车页面
    return;
  }
  return response;
});

//导出 用于请求
export default function request(config) {
  const { url = "", method = "GET", data = {}, headers = {} } = config;
  switch (method.toUpperCase()) {
    case "GET":
      return instance.get(url, { params: data });
    case "POST":
      // 如果是表单提交
      if (headers["Content-Type"] === "application/x-www-form-urlencoded") {
        const p = new URLSearchParams();
        for (const key in data) {
          p.append(key, data[key]);
        }
        return instance.post(url, p, { headers });
      }
      // 如果是文件提交
      if (headers["content-type"] === "multipart/form-data") {
        const p = new FormData();
        for (const key in data) {
          p.append(key, data[key]);
        }
        return instance.post(url, p, { headers });
      }
      // 否则就是 application/json的形式
      return instance.post(url, data);
    default:
      return instance(config);
  }
}
